import { _ } from 'meteor/underscore';
import { Apps } from '/imports/models/Apps';

Template.app_store.onCreated(function () {
  this.limit = new ReactiveVar(15);
  this.searchName = new ReactiveVar();
  this.autorun(() => {
    this.resultsSub = this.subscribe('get.apps', {}, this.limit.get());
    this.total = Counts.get('get.apps.counts');
  });
});

Template.app_store.onRendered(function () {
  const ps = new PerfectScrollbar('#app-store-body');

  $('#app-store-body').on('ps-y-reach-end', _.throttle(() => {
    let lmt = this.limit.get();
    if (this.total >= lmt) {
      this.limit.set(lmt + 15);
    }
  }, 200));
});

Template.app_store.helpers({
  results: function () {
    return Apps.find({
      name: {
        $regex: new RegExp(Template.instance().searchName.get())
      }
    }, {
      limit: Template.instance().limit.get()
    })
  },

  loading: function () {
    return !Template.instance().resultsSub.ready();
  }
});

Template.app_store.events({
  'input #app-store-input' (e, instance) {
    let text = $.trim(e.target.value);
    instance.searchName.set(text);
  },

});